#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@File    huayan.py
@IDE     ：PyCharm
@Author  ：gwj
@Date    ：2025/3/18 16:13
@use    ：
'''
import json
import random
import sys
import traceback
from datetime import datetime, timedelta
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.base import MIMEBase
from email.encoders import encode_base64
import openpyxl
import pandas as pd
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import time
import os
import requests
import fnmatch
import re
import logging
from mail import send_email
from headers import UserAgent
from chaojiying import Chaojiying_Client
from date_utils import *
from params import *


proj_name = '能量管理云'
plant_name = '浙江温州华研5台并机'
# 配置日志记录
logging.basicConfig(
    level=logging.INFO,  # 设置日志级别
    #filename=r'./log/' + proj_name + '_' + plant_name + '_' + today_yyyymmdd_str + '.log',
    format='%(asctime)s - %(levelname)s - %(message)s',  # 设置日志格式
    datefmt='%Y-%m-%d %H:%M:%S',  # 设置日期时间格式
    handlers=[
        logging.FileHandler('./log/' + proj_name + '_' + plant_name + '_' + today_yyyymmdd_str + '.log'),  # 将日志保存到本地文件，mode='a'  ：表示以追加模式打开文件，避免每次运行脚本时覆盖之前的日志
        logging.StreamHandler()  # 同时将日志输出到控制台
    ]
)
post_url = stored_plant_post_url #'http://10.0.125.43:8150/gf/postEnergyStorageData'
download_path = dowload__path_gwj #r'C:\Users\xby_ganweijian\Downloads'  #from params import *
huayan_url = 'https://auth.energy.cloud' #mgec
zname = 'huayan'
zpwd = 'Huayan123456'





def get_driver():


    options = webdriver.ChromeOptions()
    options.add_argument(f"user-agent={random.choice(UserAgent)}")
    # 关键参数配置
    options.add_argument("--disable-blink-features=AutomationControlled")  # 禁用Blink的自动化控制特征
    options.add_argument("--disable-infobars")  # 禁用信息栏
    options.add_argument("--disable-dev-shm-usage")  # 避免内存不足问题
    options.add_argument("--no-sandbox")  # 非沙箱模式（Linux服务器可能需要）
    options.add_argument("--disable-gpu")  # 禁用GPU加速（旧版系统可能需要）

    # 禁用自动化扩展（关键！）
    options.add_experimental_option("excludeSwitches", ["enable-automation"])  # 隐藏顶部的"Chrome正在受自动化测试控制"
    options.add_experimental_option("useAutomationExtension", False)  # 禁用自动化扩展
    # 添加一些选项来模拟真实用户行为
    options.add_argument("--start-maximized")  # 最大化窗口
    options.add_argument("--disable-extensions")  # 禁用扩展
    # 禁用密码保存提示
    prefs = {
        "credentials_enable_service": False,
        "profile.password_manager_enabled": False
    }
    options.add_experimental_option("prefs", prefs)
    # 启动浏览器
    browser = webdriver.Chrome(options=options)
    # 覆盖navigator.webdriver属性（Chrome 79+ 必须使用CDP）
    browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """
            Object.defineProperty(navigator, 'webdriver', {
                get: () => undefined
            });
        """
    })
    # 可选：删除Selenium的全局变量（部分网站检测window.navigator.chrome）
    browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """
            delete window.navigator.__proto__.chrome;
        """
    })
    browser.get(url=huayan_url)
    browser.maximize_window()  # 设置浏览器大小为全屏 --隐藏窗口不可使用
    browser.implicitly_wait(5)

    time.sleep(1)
    browser.find_element(By.XPATH, '//*[@placeholder="用户名/手机号/邮箱"]').send_keys(zname)
    browser.find_element(By.XPATH, '//*[@placeholder="密码"]').send_keys(zpwd)
    time.sleep(2)
    # 设置显式等待时间
    wait = WebDriverWait(browser, 3)  # 等待时间可以根据实际情况调整
    try:
        # 打印找到的元素数量 /html/body/div[1]/div/div[1]/div[2]/div/form/div[1]/div[3]/div/div/div 
        confirm_buttons = browser.find_elements(By.XPATH, '/html/body/div[1]/div/div[1]/div[2]/div/form/div[1]/div[3]/div/div/div')
        logging.info(f"找到 '点击验证' 按钮的数量：{len(confirm_buttons)}")
        # 等待“确定”按钮出现 
        if float(len(confirm_buttons)) == 1:
            confirm_button = wait.until(EC.presence_of_element_located((By.XPATH,
             '/html/body/div[1]/div/div[1]/div[2]/div/form/div[1]/div[3]/div/div/div')))
            confirm_button.click()
            logging.info("点击 '点击验证' 按钮。")
            time.sleep(3)  # 等待页面加载完成
        else:
            logging.info("未找到 '点击验证' 按钮。")
    except Exception as e:
        logging.error(f"程序运行时出现错误: {e}")        

    #点击登录按钮
    login_xpath = '//*[@id="app"]/div/div[1]/div[2]/div/form/div[2]/button/span/span'
    browser.find_element(By.XPATH, login_xpath).click()
    time.sleep(10)
    #弹窗通知
    '''
    try:
        # 打印找到的元素数量
        confirm_buttons = browser.find_elements(By.XPATH, '//div[@class="q-card__actions justify-end q-card__actions--horiz row"]/button')
        logging.info(f"找到 '确定' 按钮的数量：{len(confirm_buttons)}")
        # 等待“确定”按钮出现 
        if float(len(confirm_buttons)) == 1:
            confirm_button = wait.until(EC.presence_of_element_located((By.XPATH,
             '//div[@class="q-card__actions justify-end q-card__actions--horiz row"]/button')))
            confirm_button.click()
            logging.info("点击 '确定' 按钮。")
            time.sleep(3)  # 等待页面加载完成
        else:
            logging.info("未找到 '确定' 按钮。")
    except Exception as e:
        logging.error(f"程序运行时出现错误: {e}")
    '''
    
    #点击项目空间
    xmkj_xpath = '//*[@id="app"]/div/div[2]/div/div/div[1]/div/div/div[2]/div[3]/div/div/div/div[3]/div/div[1]/div/div'
    browser.find_element(By.XPATH, xmkj_xpath).click()
    time.sleep(2)
    logging.info("点击 '点击项目空间' 按钮。")
    # 切换到新窗口
    #logging.info('获取当前浏览器中所有打开窗口的句柄:',browser.window_handles)
    browser.switch_to.window(browser.window_handles[1])
    time.sleep(5)
    
    #点击微网能量云
    wwnly_xpath = '//*[@id="app"]/div/div/div/div/div/div[3]/div/div[2]/div[2]/div[2]/div'
    browser.find_element(By.XPATH, wwnly_xpath).click()
    logging.info("点击 '微网能量云' 按钮。")
    time.sleep(10)


    # 切换到新窗口
    #logging.info('获取当前浏览器中所有打开窗口的句柄:',browser.window_handles)
    browser.switch_to.window(browser.window_handles[2])
    time.sleep(5)
    #储能总充电量 
    wait = WebDriverWait(browser, 5)  # 等待最多 10 秒
    xpath = "//div[contains(text(), '储能总充电量')]/following-sibling::div[@class='value cursor-pointer']"
    try:
        element = wait.until(EC.presence_of_element_located((By.XPATH, xpath)))
        # 获取文本内容
        se_z_c = element.text
        #筛选出数字,包含小数点的数字
        se_z_c = re.findall(r'\d+\.\d+', se_z_c)
        if se_z_c:
            se_z_c = se_z_c[0]
            logging.info(f"储能总充电量: {se_z_c}")
        else:
            se_z_c = None
            logging.info("未在文本中找到数字。")
        time.sleep(3)
    except TimeoutException:
        logging.info("在指定时间内未找到储能总充电量元素，请检查 XPath 表达式或页面加载情况。")
        se_z_c = None
    except Exception as e:
        logging.error(f"程序运行时出现错误: {e}")
        se_z_c = None
        
    #se_z_c = browser.find_element(By.XPATH,'//div[contains(text(), '储能总充电量')]/following-sibling::div[@class='value cursor-pointer']').text
    #print("储能总充电量", se_z_c)
    
 
    #储能总放电量 
    wait = WebDriverWait(browser, 10)  # 等待最多 10 秒
    xpath = "//div[contains(text(), '储能总放电量')]/following-sibling::div[@class='value cursor-pointer']"
    try:
        element = wait.until(EC.presence_of_element_located((By.XPATH, xpath)))
        # 获取文本内容
        se_z_f = element.text
        #筛选出数字,包含小数点的数字
        se_z_f = re.findall(r'\d+\.\d+', se_z_f)
        if se_z_f:
            se_z_f = se_z_f[0]
            logging.info(f"储能总放电量: {se_z_f}")
        else:
            se_z_f = None
            logging.info("未在文本中找到数字。")
        time.sleep(3)
    except TimeoutException:
        logging.info("在指定时间内未找到储能总放电量元素，请检查 XPath 表达式或页面加载情况。")
        se_z_f = None
    except Exception as e:
        logging.error(f"程序运行时出现错误: {e}")
        se_z_f = None
    #累计收益
    #total_earnings = browser.find_element(By.XPATH,'//*[@id="QrJ9h7OAe"]/div[2]/div/div/div/div[8]/div/div[2]/div[2]').text
    #print("累计收益", total_earnings)
    wait = WebDriverWait(browser, 5)  # 等待最多 10 秒
    xpath = "//div[contains(text(), '累计收益')]/following-sibling::div[@class='value cursor-pointer']"
    try:
        element = wait.until(EC.presence_of_element_located((By.XPATH, xpath)))
        # 获取文本内容
        total_earnings = element.text
        #筛选出数字,包含小数点的数字
        total_earnings = re.findall(r'\d+\.\d+', total_earnings)
        if total_earnings:
            total_earnings = total_earnings[0]
            logging.info(f"累计收益: {total_earnings}")
        else:
            total_earnings = None
            logging.info("未在文本中找到数字。")
        time.sleep(3)
    except TimeoutException:
        logging.info("在指定时间内未找到累计收益元素，请检查 XPath 表达式或页面加载情况。")
        total_earnings = None
    except Exception as e:
        logging.error(f"程序运行时出现错误: {e}")
        total_earnings = None

    #点击储能总充电量,下载日月年数据
    #日
    try:
        # 等待页面加载完成,下载日数据
        WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.XPATH, '//*[@id="QrJ9h7OAe"]/div[2]/div/div/div/div[5]/div/div[2]/div[2]'))
        )
        # 点击“日”按钮
        month_total_earnings_xpath = '//*[@id="QrJ9h7OAe"]/div[2]/div/div/div/div[5]/div/div[2]/div[2]'
        month_button = browser.find_element(By.XPATH, month_total_earnings_xpath)
        month_button.click()

        # 等待下载按钮出现
        WebDriverWait(browser, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'))
        )

        # 点击下载按钮
        download_xpath = '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'
        download_button = browser.find_element(By.XPATH, download_xpath)
        download_button.click()
        logging.info("下载储能总充电量日数据成功")
    except TimeoutException:
        logging.warning("在指定时间内未找到储能总充电量元素，请检查页面加载情况。")
    except NoSuchElementException:
        logging.warning("未找到储能总充电量元素，请检查 XPath 表达式。")
    except Exception as e:
        logging.error(f"下载储能总充电（日）时出现错误: {e}")
    time.sleep(20)


    try:
        # 等待页面加载完成,下载月数据
        WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.XPATH, '//span[@class="el-radio-button__inner" and text()="月"]'))
        )
        # 点击“月”按钮
        month_total_earnings_xpath = '//span[@class="el-radio-button__inner" and text()="月"]'
        month_button = browser.find_element(By.XPATH, month_total_earnings_xpath)
        month_button.click()

        # 等待下载按钮出现
        WebDriverWait(browser, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'))
        )

        # 点击下载按钮
        download_xpath = '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'
        download_button = browser.find_element(By.XPATH, download_xpath)
        download_button.click()
        logging.info("下载储能总充电量月数据成功")
    except TimeoutException:
        logging.warning("在指定时间内未找到储能总充电量元素，请检查页面加载情况。")
    except NoSuchElementException:
        logging.warning("未找到储能总充电量元素，请检查 XPath 表达式。")
    except Exception as e:
        logging.error(f"下载储能总充电（月）时出现错误: {e}")
    time.sleep(20)

    
    try:
        # 等待页面加载完成,下载年数据
        WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.XPATH, '//span[@class="el-radio-button__inner" and text()="年"]'))
        )
        # 点击“年”按钮
        month_total_earnings_xpath = '//span[@class="el-radio-button__inner" and text()="年"]'
        month_button = browser.find_element(By.XPATH, month_total_earnings_xpath)
        month_button.click()

        # 等待下载按钮出现
        WebDriverWait(browser, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'))
        )

        # 点击下载按钮
        download_xpath = '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'
        download_button = browser.find_element(By.XPATH, download_xpath)
        download_button.click()
        logging.info("下载储能总充电量年数据成功")
    except TimeoutException:
        logging.warning("在指定时间内未找到储能总充电量元素，请检查页面加载情况。")
    except NoSuchElementException:
        logging.warning("未找到储能总充电量元素，请检查 XPath 表达式。")
    except Exception as e:
        logging.error(f"下载储能总充电（年）时出现错误: {e}")
    time.sleep(20)

    #关闭下载窗口
    colse_xpath = '/html/body/div[15]/div/div/div/header/button'
    browser.find_element(By.XPATH, colse_xpath).click()
    logging.info("关闭储能总充电量窗口")
    time.sleep(2)

   #点击储能总放电量,下载日月年数据
    #日
    try:
        # 等待页面加载完成,下载日数据
        WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.XPATH, '//*[@id="QrJ9h7OAe"]/div[2]/div/div/div/div[6]/div/div[2]/div[2]'))
        )
        # 点击“日”按钮
        month_total_earnings_xpath = '//*[@id="QrJ9h7OAe"]/div[2]/div/div/div/div[6]/div/div[2]/div[2]'
        month_button = browser.find_element(By.XPATH, month_total_earnings_xpath)
        month_button.click()

        # 等待下载按钮出现
        WebDriverWait(browser, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'))
        )

        # 点击下载按钮
        download_xpath = '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'
        download_button = browser.find_element(By.XPATH, download_xpath)
        download_button.click()
        logging.info("下载储能总放电量日数据成功")
    except TimeoutException:
        logging.warning("在指定时间内未找到储能总放电量元素，请检查页面加载情况。")
    except NoSuchElementException:
        logging.warning("未找到储能总放电量元素，请检查 XPath 表达式。")
    except Exception as e:
        logging.error(f"下载储能总放电（日）时出现错误: {e}")
    time.sleep(20)


    try:
        # 等待页面加载完成,下载月数据
        WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.XPATH, '//span[@class="el-radio-button__inner" and text()="月"]'))
        )
        # 点击“月”按钮
        month_total_earnings_xpath = '//span[@class="el-radio-button__inner" and text()="月"]'
        month_button = browser.find_element(By.XPATH, month_total_earnings_xpath)
        month_button.click()

        # 等待下载按钮出现
        WebDriverWait(browser, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'))
        )

        # 点击下载按钮
        download_xpath = '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'
        download_button = browser.find_element(By.XPATH, download_xpath)
        download_button.click()
        logging.info("下载储能总放电量月数据成功")
    except TimeoutException:
        logging.warning("在指定时间内未找到储能总放电量元素，请检查页面加载情况。")
    except NoSuchElementException:
        logging.warning("未找到储能总放电量元素，请检查 XPath 表达式。")
    except Exception as e:
        logging.error(f"下载储能总放电（月）时出现错误: {e}")
    time.sleep(20)
    
    try:
        # 等待页面加载完成,下载年数据
        WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.XPATH, '//span[@class="el-radio-button__inner" and text()="年"]'))
        )
        # 点击“年”按钮
        month_total_earnings_xpath = '//span[@class="el-radio-button__inner" and text()="年"]'
        month_button = browser.find_element(By.XPATH, month_total_earnings_xpath)
        month_button.click()

        # 等待下载按钮出现
        WebDriverWait(browser, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'))
        )

        # 点击下载按钮
        download_xpath = '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'
        download_button = browser.find_element(By.XPATH, download_xpath)
        download_button.click()
        logging.info("下载储能总放电量年数据成功")
    except TimeoutException:
        logging.warning("在指定时间内未找到储能总放电量元素，请检查页面加载情况。")
    except NoSuchElementException:
        logging.warning("未找到储能总放电量元素，请检查 XPath 表达式。")
    except Exception as e:
        logging.error(f"下载储能总放电（年）时出现错误: {e}")
    time.sleep(20)
    
    #关闭下载窗口
    colse_xpath = '/html/body/div[15]/div/div/div/header/button'
    browser.find_element(By.XPATH, colse_xpath).click()
    logging.info("关闭储能总放电量窗口")
    time.sleep(2)

    '''
    #点击储能总放电量,下载日月年数据
    #日
    try:
        day_se_z_f_xpath = '//*[@id="QrJ9h7OAe"]/div[2]/div/div/div/div[6]/div/div[2]/div[2]'
        browser.find_element(By.XPATH, day_se_z_f_xpath).click()
        download_xpath = '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'
        browser.find_element(By.XPATH, download_xpath).click()
        logging.info("下载储能总放电量日数据成功")
        time.sleep(3)
    except TimeoutException:
        logging.warning("在指定时间内未找到储能总放电量元素，请检查页面加载情况。")
    except NoSuchElementException:
        logging.warning("未找到储能总放电量元素，请检查 XPath 表达式。")
    time.sleep(5)
    #月
    month_se_z_f_xpath = '//span[@class="el-radio-button__inner" and text()="月"]'
    browser.find_element(By.XPATH, month_se_z_f_xpath).click()
    download_xpath = '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'
    browser.find_element(By.XPATH, download_xpath).click()
    logging.info("下载储能总放电量月数据成功")
    time.sleep(5)
    #年
    year_se_z_f_xpath = '//span[@class="el-radio-button__inner" and text()="年"]'
    browser.find_element(By.XPATH, year_se_z_f_xpath).click()
    download_xpath = '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'
    browser.find_element(By.XPATH, download_xpath).click()
    logging.info("下载储能总放电量年数据成功")
    time.sleep(5)
    
    #关闭下载窗口
    colse_xpath = '/html/body/div[15]/div/div/div/header/button'
    browser.find_element(By.XPATH, colse_xpath).click()
    time.sleep(5)

    #点击累计收益,下载日月年数据
    #日
    try:
        day_se_z_f_xpath = '//*[@id="QrJ9h7OAe"]/div[2]/div/div/div/div[8]/div/div[2]/div[2]'
        browser.find_element(By.XPATH, day_se_z_f_xpath).click()
        download_xpath = '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'
        browser.find_element(By.XPATH, download_xpath).click()
        logging.info("下载累计收益日数据成功")
        time.sleep(3)
    except TimeoutException:
        logging.warning("在指定时间内未找到累计收益元素，请检查页面加载情况。")
    except NoSuchElementException:
        logging.warning("未找到累计收益元素，请检查 XPath 表达式。")
    time.sleep(5)
    #月
    month_total_earnings_xpath = '//span[@class="el-radio-button__inner" and text()="月"]'
    browser.find_element(By.XPATH, month_total_earnings_xpath).click()
    download_xpath = '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'
    browser.find_element(By.XPATH, download_xpath).click()
    logging.info("下载累计收益月数据成功")
    time.sleep(5)
    #年
    year_total_earnings_xpath = '//span[@class="el-radio-button__inner" and text()="年"]'
    browser.find_element(By.XPATH, year_total_earnings_xpath).click()
    download_xpath = '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'
    browser.find_element(By.XPATH, download_xpath).click()
    logging.info("下载累计收益年数据成功")
    time.sleep(5)
    '''
    #点击累计收益,下载日月年数据
    #日
    try:
        # 等待页面加载完成,下载日数据
        WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.XPATH, '//*[@id="QrJ9h7OAe"]/div[2]/div/div/div/div[8]/div/div[2]/div[2]'))
        )
        # 点击“日”按钮
        month_total_earnings_xpath = '//*[@id="QrJ9h7OAe"]/div[2]/div/div/div/div[8]/div/div[2]/div[2]'
        month_button = browser.find_element(By.XPATH, month_total_earnings_xpath)
        month_button.click()

        # 等待下载按钮出现
        WebDriverWait(browser, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'))
        )

        # 点击下载按钮
        download_xpath = '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'
        download_button = browser.find_element(By.XPATH, download_xpath)
        download_button.click()
        logging.info("下载累计收益日数据成功")
    except TimeoutException:
        logging.warning("在指定时间内未找到累计收益元素，请检查页面加载情况。")
    except NoSuchElementException:
        logging.warning("未找到累计收益元素，请检查 XPath 表达式。")
    except Exception as e:
        logging.error(f"下载累计收益（日）时出现错误: {e}")
    time.sleep(20)


    try:
        # 等待页面加载完成,下载月数据
        WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.XPATH, '//span[@class="el-radio-button__inner" and text()="月"]'))
        )
        # 点击“月”按钮
        month_total_earnings_xpath = '//span[@class="el-radio-button__inner" and text()="月"]'
        month_button = browser.find_element(By.XPATH, month_total_earnings_xpath)
        month_button.click()

        # 等待下载按钮出现
        WebDriverWait(browser, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'))
        )

        # 点击下载按钮
        download_xpath = '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'
        download_button = browser.find_element(By.XPATH, download_xpath)
        download_button.click()
        logging.info("下载累计收益月数据成功")
    except TimeoutException:
        logging.warning("在指定时间内未找到累计收益元素，请检查页面加载情况。")
    except NoSuchElementException:
        logging.warning("未找到累计收益元素，请检查 XPath 表达式。")
    except Exception as e:
        logging.error(f"下载累计收益（月）时出现错误: {e}")
    time.sleep(20)
    
    try:
        # 等待页面加载完成,下载年数据
        WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.XPATH, '//span[@class="el-radio-button__inner" and text()="年"]'))
        )
        # 点击“年”按钮
        month_total_earnings_xpath = '//span[@class="el-radio-button__inner" and text()="年"]'
        month_button = browser.find_element(By.XPATH, month_total_earnings_xpath)
        month_button.click()

        # 等待下载按钮出现
        WebDriverWait(browser, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'))
        )

        # 点击下载按钮
        download_xpath = '//*[@class="i-mdi-download absolute download-icon right-4 top-2 cursor-pointer z-10"]'
        download_button = browser.find_element(By.XPATH, download_xpath)
        download_button.click()
        logging.info("下载累计收益年数据成功")
    except TimeoutException:
        logging.warning("在指定时间内未找到累计收益元素，请检查页面加载情况。")
    except NoSuchElementException:
        logging.warning("未找到累计收益元素，请检查 XPath 表达式。")
    except Exception as e:
        logging.error(f"下载累计收益（年）时出现错误: {e}")
    time.sleep(10)
    #关闭累计收益下载窗口
    colse_xpath = '/html/body/div[15]/div/div/div/header/button'
    browser.find_element(By.XPATH, colse_xpath).click()
    logging.info("关闭累计收益窗口")
    time.sleep(2)

    
    return browser,se_z_c,se_z_f, total_earnings





def rename_files_and_store_paths(directory):
    #在指定目录下找到特定文件并重命名，同时存储重命名后的文件路径
    # 定义目标文件名及其对应的重命名规则
    target_files = {
        "储能总充电量.xlsx": "储能总充电量_日.xlsx",
        "储能总充电量 (1).xlsx": "储能总充电量_月.xlsx",
        "储能总充电量 (2).xlsx": "储能总充电量_年.xlsx",
        "储能总放电量.xlsx": "储能总放电量_日.xlsx",
        "储能总放电量 (1).xlsx": "储能总放电量_月.xlsx",
        "储能总放电量 (2).xlsx": "储能总放电量_年.xlsx",
        "累计收益.xlsx": "累计收益_日.xlsx",
        "累计收益 (1).xlsx": "累计收益_月.xlsx",
        "累计收益 (2).xlsx": "累计收益_年.xlsx"
    }
    # 用于存储重命名后的文件路径
    renamed_paths = []
    # 获取目录中的所有文件名
    all_files = os.listdir(directory)
    # 按照 target_files 的顺序处理文件
    for original_filename, new_filename in target_files.items():
        if original_filename in all_files:  # 检查文件是否存在
            original_path = os.path.join(directory, original_filename)  # 原文件路径
            new_path = os.path.join(directory, new_filename)  # 新文件路径

            # 重命名文件
            try:
                os.rename(original_path, new_path)
                logging.info(f"文件 {original_path} 已重命名为 {new_path}")
                renamed_paths.append(new_path)
            except Exception as e:
                logging.error(f"重命名文件 {original_path} 时发生错误: {e}")
        else:
            logging.warning(f"未找到文件 {original_filename}，跳过重命名。")
            #测试用例
            renamed_paths = [directory+'\\储能总充电量_日.xlsx',directory+'\\储能总充电量_月.xlsx',directory+'\\储能总充电量_年.xlsx'
                            ,directory+'\\储能总放电量_日.xlsx',directory+'\\储能总放电量_月.xlsx',directory+'\\储能总放电量_年.xlsx'
                            ,directory+'\\累计收益_日.xlsx',directory+'\\累计收益_月.xlsx',directory+'\\累计收益_年.xlsx']
    '''
    target_files_2 = {
        "储能总充电量.xlsx": "储能总充电量_日.xlsx",
        "储能总充电量 (1).xlsx": "储能总充电量_月.xlsx",
        "储能总充电量 (2).xlsx": "储能总充电量_年.xlsx"
    }
    # 用于存储重命名后的文件路径
    renamed_paths_2 = []
    # 获取目录中的所有文件名
    all_files = os.listdir(directory)
    # 按照 target_files_2 的顺序处理文件
    for original_filename, new_filename in target_files_2.items():
        if original_filename in all_files:  # 检查文件是否存在
            original_path = os.path.join(directory, original_filename)  # 原文件路径
            new_path = os.path.join(directory, new_filename)  # 新文件路径

            # 重命名文件
            try:
                os.rename(original_path, new_path)
                logging.info(f"文件 {original_path} 已重命名为 {new_path}")
                renamed_paths_2.append(new_path)
            except Exception as e:
                logging.error(f"重命名文件 {original_path} 时发生错误: {e}")
        else:
            logging.warning(f"未找到文件 {original_filename}，跳过重命名。")
            #测试用例
            renamed_paths_2 = [directory+'\\储能总充电量_日.xlsx',directory+'\\储能总充电量_月.xlsx'
                            ,directory+'\\储能总充电量_年.xlsx']
    '''
    return renamed_paths #,renamed_paths_2
    

def main(static_date_str):
    logging.info(f"参数static_date_str为:{static_date_str}")
    if static_date_str != (today - timedelta(days=1)).strftime("%Y%m%d"):
        static_date_str = (today - timedelta(days=1)).strftime("%Y%m%d")
    if not os.path.exists(download_path):
        os.makedirs(download_path)
    directory = download_path # 替换为你的下载文件存放目录
    
    # 遍历目录中的所有文件
    try:
        for filename in os.listdir(directory):
            # 检查文件是否以指定前缀开头且是 .xlsx 文件
            if (filename.startswith("储能总充电量") or filename.startswith("储能总放电量") or filename.startswith("累计收益")
                )and filename.endswith(".xlsx"):
                file_path = os.path.join(directory, filename)  # 获取完整文件路径
                os.remove(file_path)  # 删除文件
                logging.info(f"Deleted: {file_path}")
    except Exception as e:
        logging.error(f"删除文件时出现错误: {e}")
       
    #启动浏览器
    # 在原代码中，`get_driver` 函数返回的是一个元组 (browser, total_power_consumption, month_power_consumption)，
    # 因此需要从元组中提取出 `browser` 对象，然后再调用 `quit` 方法关闭浏览器。
    browser,se_z_c, se_z_f, total_earnings = get_driver()
    browser.quit()

    # 调用函数并获取重命名后的文件路径
    renamed_paths = rename_files_and_store_paths(directory)
    # 在后续代码中分别打印出这三个文件的路径
    try:
        if len(renamed_paths) >= 9:
            logging.info("重命名后的文件路径：")
            logging.info(f"充日文件路径: {renamed_paths[0]}")
            logging.info(f"充月文件路径: {renamed_paths[1]}")
            logging.info(f"充年文件路径: {renamed_paths[2]}")
            logging.info(f"放日文件路径: {renamed_paths[3]}")
            logging.info(f"放月文件路径: {renamed_paths[4]}")
            logging.info(f"放年文件路径: {renamed_paths[5]}")
            logging.info(f"收益日文件路径: {renamed_paths[6]}")
            logging.info(f"收益月文件路径: {renamed_paths[7]}")
            logging.info(f"收益年文件路径: {renamed_paths[8]}")
    except Exception as e:
        logging.error(f"打印出这9个文件的路径文件时出现错误: {e}")
    
    # 分别读取Excel文件，并将其内容转换为  DataFrame
    #循环读取file_path_d,并将其内容转换为  DataFrame
    data_day = []
    data_other = []
    for file_path in renamed_paths:
        index = renamed_paths.index(file_path)
        if file_path is not None:
            if index in [0, 3, 6]:
                try:
                    # 读取Excel文件，并将其内容转换为 DataFrame
                    df = pd.read_excel(file_path, engine="openpyxl")
                    logging.info(f"成功读取日文件: {file_path}")
                    # 使用正则表达式匹配日期格式
                    pattern = r"(\d{4}-\d{2}-\d{2})"  # 匹配形如 YYYY-MM-DD 的日期
                    date_str = re.findall(pattern, df.iloc[-2, 0])
                    date_str = datetime.strptime(date_str[0], '%Y-%m-%d').strftime('%Y%m%d')
                    logging.info(date_str)
                    logging.info(static_date_str)
                    if date_str == static_date_str:
                        logging.info(df.iat[-2, 1])
                        #保存数据
                        data_day.append(df.iat[-2, 1])
                except Exception as e:
                    logging.error(f"读取文件 {file_path} 时出现错误: {e}")
            else:
                try:
                    # 读取Excel文件，并将其内容转换为 DataFrame
                    df = pd.read_excel(file_path, engine="openpyxl")
                    logging.info(f"成功读取非日文件: {file_path}")
                    logging.info(df.iat[-1, 1])
                    #保存数据
                    data_other.append(df.iat[-1, 1])
                except Exception as e:
                    logging.error(f"读取文件 {file_path} 时出现错误: {e}")

        else:
            logging.warning(f"文件路径为 None，跳过该文件。")
    logging.info(data_day)
    logging.info(data_other)
    try:
        if len(data_day) == 3 and len(data_other) == 6:
            logging.info("日月年数据获取成功")
            # 数据处理
            data =  {"plant_name": '浙江温州华研5台并机储能',
                "stored_energy_url": huayan_url,
                "update_time": today_yyyymmdd_str,
                "static_date": static_date_str,
                "eday_c_z": str(data_day[0]),
                "eday_c_j": "",
                "eday_c_f": "",
                "eday_c_p": "",
                "eday_c_g": "",
                "eday_c_sg": "",
                "eday_f_z": str(data_day[1]),
                "eday_f_j": "",
                "eday_f_f": "",
                "eday_f_p": "",
                "eday_f_g": "",
                "eday_f_sg": "",
                "etot_c": str(se_z_c),
                "etot_f": str(se_z_f),
                "eyear_c":str(data_other[1]) ,
                "eyear_f": str(data_other[3]),
                "emonth_c": str(data_other[0]),
                "emonth_f": str(data_other[2]),
                "day_earnings": str(data_day[2]),
                "month_earnings": str(data_other[4]),
                "year_earnings": str(data_other[5]),
                "total_earnings": str(total_earnings) }
            # 将数据转换为JSON格式
            json_data = json.dumps(data)
            response = requests.post(url=post_url, data=json_data)
            logging.info(response.text)
            logging.info(response.status_code)
            success_flag = response.json().get('code') == 0
            send_email(proj_name, plant_name, static_date_str, success_flag)
        else:
            logging.info("日月年数据获取失败")
            send_email(proj_name, plant_name, static_date_str, is_success=False)
    except Exception as e:
        logging.error(f"获取数据时出现错误: {e}")
        # 构建错误信息
        exc_type, exc_value, exc_tb = sys.exc_info()
        tb_list = traceback.format_exception(exc_type, exc_value, exc_tb)
        error_msg = f"""
                    发生未处理异常：
                    异常类型：{exc_type.__name__}
                    错误信息：{str(exc_value)}
                    异常位置：{tb_list[-2].strip()}
                    完整堆栈：
                    {''.join(tb_list)}
                    """
        send_email(proj_name, plant_name, static_date_str, is_success=False, error=error_msg)    
    

    
if __name__ == '__main__':
    max_retries = 1  # 最大重试次数
    retries = 0
    while retries <= max_retries:
        try:
            main(yesterday_yyyymmdd_str)
            break  # 如果没有错误，跳出重试循环
        #出现错误再重跑一次，尽量避免可能网络延迟导致xpath获取失败的情况
        except Exception as e:
            retries += 1
            if retries <= max_retries:
                logging.error(f"程序运行时出现错误: {e}，正在进行第 {retries} 次重试...")
            else:
                logging.info("已达到最大重试次数，停止重试。")
                logging.error(f"程序运行时出现错误: {e}")
    

